package com.soft.base.util;

import com.soft.base.enums.ValueNameEnum;
import com.soft.base.exception.ParamException;
import lombok.Data;

import java.lang.reflect.Field;
import java.lang.reflect.Modifier;
import java.util.HashMap;
import java.util.Map;
/**
 * class
 *
 * @author user
 * @date 2020/06/05
 */
public class DumpUtil {

    public static Map<String, Object> dumpFinalFields(Class cls) {
        HashMap<String, Object> map = new HashMap<>(1);
        try {
            for (Field field : cls.getDeclaredFields()) {
                if (!Modifier.isPublic(field.getModifiers()) || !Modifier.isFinal(field.getModifiers())) {
                    continue;
                }
                if (field.getType().isAssignableFrom(int.class)) {
                    map.put(field.getName(), field.getInt(null));
                } else if (field.getType().isAssignableFrom(long.class)) {
                    map.put(field.getName(), field.getLong(null));
                } else {
                    ParamException.throwException("Unsupported field type in DumpUtil.dumpFinalFields");
                }
            }
        } catch (IllegalAccessException e) {
        }
        return map;
    }

    @Data
    public static class EnumDumpItem {
        private String key;
        private Object value;
        private String name;
    }

    public static Map<String, EnumDumpItem> dumpEnum(Class enumClass) {
        HashMap<String, EnumDumpItem> map = new HashMap<>(1);
        for (Object o : enumClass.getEnumConstants()) {
            if (o instanceof ValueNameEnum) {
                EnumDumpItem item = new EnumDumpItem();
                item.setKey(o.toString());
                item.setValue(((ValueNameEnum) o).getValue());
                item.setName(((ValueNameEnum) o).getName());
                map.put(item.getKey(), item);
            } else {
                ParamException.throwException("Unsupported enumClass in DumpUtil.dumpEnum");
            }
        }
        return map;
    }
}
